package com.cy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Graph <T extends SubStepAbstract>{
    private final Map<T, Set<T>> preMap = new HashMap<>();

    public Graph(List<T> nodes) {
        for (T node : nodes) {
            preMap.put(node,new HashSet<>());
        }
    }

    public void setChild(T parent,T child) {
        parent.setChild(child);
        child.preNode(parent);
        preMap.get(child).add(parent);
    }

    public void run() throws InterruptedException {
        List<T> headers = this.getHeader();
        int n = headers.size();
        Thread[] threads = new Thread[n];
        for (int i = 0; i < n; i++) {
            threads[i] = new Thread(headers.get(i));
            threads[i].start();
        }
        for (Thread t : threads) {
            t.join();
        }
    }

    // 获取所有根节点
    public List<T> getHeader() {
        List<T> header = new ArrayList<>();
        for (T node : this.preMap.keySet()) {
            if (this.preMap.get(node).isEmpty()) {
                header.add(node);
            }
        }
        return header;
    }


}
